/**
 * 
 */
package com.lvan.exception.resolver;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.lvan.bean.BaseException;

/**
 * @author Stern He<br>
 *         2013-9-27<br>
 * @version 1.0.0.0
 */
public class ExceptionHandler implements HandlerExceptionResolver {

	@Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception e) {
        ModelAndView mv = new ModelAndView();
        Map<String, String> m = new HashMap<String, String>();
        if (e instanceof BaseException) {
        	BaseException be = (BaseException) e;
        	m.put("code", be.getErrorCode());
        	m.put("message", be.getMessage());
        	m.put("title", be.getTitle());
        	m.put("op", be.getOp());
        	if(!(request.getHeader("accept").indexOf("application/json") > -1 || (request  
                    .getHeader("X-Requested-With")!= null && request  
                    .getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
	            mv.setViewName("failure");
        	}
        	mv.addAllObjects(m);
        } else {
            mv.setViewName("error");
        }
        return mv;
    }
    
}
